<template>
  <div :style="{ textAlign: countStyle ? countStyle.align : '' }">
    <count-to :style="getStyle()" :start-val="startNumber" :end-val="modelValue || endNumber" :duration="duration" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { CountTo } from '@/components/CountTo';

export default defineComponent({
  name: 'AnvilCount',
  components: { CountTo },
  props: {
    modelValue: {
      type: Number,
      default: undefined
    },
    startNumber: {
      type: Number,
      default: 0
    },
    endNumber: {
      type: Number,
      default: 1000
    },
    duration: {
      type: Number,
      default: undefined
    },
    countStyle: {
      type: Object,
      default: () => {}
    },
    customCssObj: {
      type: String,
      default: ''
    }
  },
  methods: {
    getStyle() {
      if (!this.countStyle) {
        return {};
      }
      let style = {
        color: this.countStyle.color,
        fontSize: this.countStyle.fontSize ? this.countStyle.fontSize + 'px' : undefined,
        lineHeight: this.countStyle.fontSize ? this.countStyle.fontSize + 'px' : undefined,
        backgroundColor: this.countStyle.backgroundColor,
        fontWeight: this.countStyle.bold ? 'bold' : 'normal',
        fontStyle: this.countStyle.italic ? 'italic' : 'normal',
        textDecoration: this.countStyle.underline ? 'underline' : 'none',
        'white-space': 'pre-wrap',
        ...this.getCustomCss()
      };
      return style;
    },
    getCustomCss() {
      const cssObj = {};
      try {
        const Attrs = this.customCssObj.split('\n');
        Attrs.forEach((element) => {
          const css = element.replaceAll(' ', '').split(':');
          if (css && css.length == 2) {
            cssObj[css[0]] = css[1];
          }
        });
      } catch (e) {
        console.log('error!', e);
      } finally {
        return cssObj;
      }
    }
  }
});
</script>
